<template>
  <div class="login">
    <van-form @submit="handleLogin">
      <van-cell-group inset>
        <van-field
          v-model="phone"
          name="手机号码"
          label="手机号码"
          placeholder="手机号码"
          :rules="[{ required: true, message: '请填写电话号码' }]"
        />
        <van-field
          v-model="code"
          center
          clearable
          label="短信验证码"
          placeholder="请输入短信验证码"
      >
    <template #button>
      <van-button size="small" type="primary" @click="handleGetCode">发送验证码</van-button>
    </template>
    </van-field>
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup lang="ts">
import { showSuccessToast} from 'vant';
import { ref } from 'vue'
import { useRouter } from 'vue-router'

import {getCode} from '../../api/login'
import useUserStore from '../../store/modules/user'

const router = useRouter()

const store = useUserStore()

const phone = ref<string>('15286303220')
const code = ref<string>('')

// 登录表单提交
const handleLogin = async() => {
  // 进行手机号码的非空校验
  const reult: any = await store.asyncLoginAction({
    phone: phone.value,
    code: code.value
  })
  // 如果登录成功则跳转页面。否则提示错误
  if (reult) {
    router.push('/mine')
    showSuccessToast('登录成功')
  } else {
    showSuccessToast('用户名或密码错误')
  }
}

// 获取验证码
const handleGetCode = async() => {
  // 手机号码非空校验
  const result: any = await getCode(phone.value)
  code.value = result.code
}

</script>

<style scoped>

</style>
